import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputVal: '',
    nextId: 5,
    keyWords: 'all'
  },
  mutations: {
    initList(state, data) {
      state.list = data
    },
    changeInput(state, val) {
      state.inputVal = val
    },
    addListItem(state) {
      const obj = {
        id: state.nextId++,
        info: state.inputVal,
        done: false
      }
      state.list.push(obj)
    },
    removeListItem(state, id) {
      state.list = state.list.filter((val) => {
        return val.id !== id
      })
    },
    changeState(state, row) {
      let i = state.list.findIndex(x => x.id === row.id)
      state.list[i].done = row.done
    },
    clearDone(state) {
      state.list = state.list.filter(x => !x.done)
    },
    controlType(state, type) {
      state.keyWords = type
    }
  },
  actions: {
    getList(context) {
      axios.get(`/list.json`).then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  getters: {
    doneCount(state) {
      return state.list.filter(x => !x.done).length
    },
    infolist(state) {
      if (state.keyWords === 'all') {
        return state.list
      } else if (state.keyWords === 'undone') {
        return state.list.filter(x => !x.done)
      } else if (state.keyWords === 'done') {
        return state.list.filter(x => x.done)
      }
      return state.list
    }
  }
})
